package com.ruifu.doc.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhzncloud.cloud.common.security.service.CloudUser;
import com.ruifu.common.config.ActConstants;
import com.ruifu.common.feign.RemoteActService;
import com.ruifu.common.feign.RemoteWorkSheetService;
import com.ruifu.common.po.DmDocc;
import com.ruifu.common.po.ObjectPermissionsAuthorization;
import com.ruifu.common.utils.FindPermissionCommon;
import com.ruifu.common.vo.actanddoc.ProccessTaskVO;
import com.ruifu.common.vo.worksheet.WsCommonSheet;
import com.ruifu.doc.conf.DocFinal;
import com.ruifu.doc.mapper.DmDoccMapper;
import com.ruifu.doc.mapper.ObjectPermissionsAuthorizationMapper;
import com.ruifu.doc.permissionsObject.WsPermissionObject;
import com.ruifu.doc.service.PermissionsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author lcq
 * @create 2020/5/18
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class PermissionsServiceImpl extends ServiceImpl<ObjectPermissionsAuthorizationMapper, ObjectPermissionsAuthorization> implements PermissionsService {

    @Autowired(required = false)
    private ObjectPermissionsAuthorizationMapper permissionsMapper;

    @Autowired
    PermissionsService permissionsService;

    @Autowired(required = false)
    DmDoccMapper dmDoccMapper;

    @Autowired(required = false)
    RemoteWorkSheetService remoteWorkSheetService;

    @Autowired
    RemoteActService remoteActService;

    /**
     * 文档权限初始化
     * @param sourceTenantId  源账套
     * @param newTenantId 目标账套
     * @return
     */
    @Override
    public Boolean insertPermission(Integer sourceTenantId, Integer newTenantId) {
        List<ObjectPermissionsAuthorization> permissionsList = permissionsMapper.selectList(Wrappers.<ObjectPermissionsAuthorization>lambdaQuery()
                .eq(ObjectPermissionsAuthorization::getSetSid, sourceTenantId));

        for (ObjectPermissionsAuthorization permission : permissionsList) {
            permission.setPermissionsAuthorizationId(null);
            permission.setSetSid(Long.valueOf(newTenantId));
        }
        return permissionsService.saveBatch(permissionsList);
    }

    /**
     * 文档类型初始化
     * @param sourceTenantId  源账套
     * @param newTenantId 目标账套
     * @return
     */
    @Override
    public Boolean insertDocType(Integer sourceTenantId, Integer newTenantId) {
        List<DmDocc> dmDoccList = dmDoccMapper.selectByTenAntId(sourceTenantId);
        for (DmDocc dmDocc : dmDoccList) {
            dmDocc.setDcDoccId(null);
            dmDocc.setDcSetSid(newTenantId);
        }
        try {
            for (DmDocc dmDocc : dmDoccList) {
                dmDoccMapper.insertType(dmDocc);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 工作单权限计算
     * @param wsCommonSheet  工作单对象
     * @return
     */
    @Override
    public String findPermissionByWorkFormId(WsCommonSheet wsCommonSheet, CloudUser cloudUser) {
        //数据对象
        WsPermissionObject wsPermissionObject = new WsPermissionObject();
        wsPermissionObject.ws = wsCommonSheet;
        wsPermissionObject.userId= cloudUser.getId();
        wsPermissionObject.permissionsService = new PermissionsServiceImpl();
        //获取当工作单所处节点的信息
        //变更单类别 问题报告单:0   变更申请单:1 变更通知单:2 作废通知单:3
        // setCmFeginClassFlag就是把这个值加了个"-" -pes
        switch (wsCommonSheet.getCmWsClassFlag()){
            case "0":
                wsCommonSheet.setCmFeginClassFlag(ActConstants.PROBLEM_REPORT_SUFFIX);
                break;
            case "1":
                wsCommonSheet.setCmFeginClassFlag(ActConstants.CHANGE_REQUEST_SUFFIX);
                break;
            case "2":
                wsCommonSheet.setCmFeginClassFlag(ActConstants.CHANGE_NOTIFICATION_SUFFIX);
                break;
            case "3":
                wsCommonSheet.setCmFeginClassFlag(ActConstants.VOID_NOTICE_SUFFIX);
                break;
            default:break;

        }
        ProccessTaskVO nowTaskNode = remoteActService.getNowTaskNode(wsCommonSheet.getCmId()+wsCommonSheet.getCmFeginClassFlag());
        if (nowTaskNode != null) {
            log.info("处于流程中的工作单为：" + wsCommonSheet.getCmName());
            //获取流程当前节点名称
            wsPermissionObject.currentStep = nowTaskNode.getTaskName();
            log.info("当前节点名称：" + nowTaskNode.getTaskName());
            //集合转字符串
            wsPermissionObject.nodeUserIdList = StringUtils.join(nowTaskNode.getUserIdList(), ",");
            log.info("当前节点办理人(可多个)：" + wsPermissionObject.nodeUserIdList);
            //得到文档类型权限定义列表
            List<ObjectPermissionsAuthorization> objectPermissionsList =
                    permissionsMapper.findByObjectTypeId(DocFinal.WS, cloudUser);

            String permission = FindPermissionCommon.findPermissionByUserIdAndPtId(cloudUser, wsPermissionObject, objectPermissionsList);
            log.info(wsCommonSheet.getCmName() + "工作单权限为：" + permission);
            return permission;

        }
        return null;
    }

    /**
     * 变更单查看权限
     * @param userId 当前用户id
     * @param nodeUserIdList 节点办理人字符串
     * @return
     */
    @Override
    public Boolean isNodeHandlerUser(Integer userId, String nodeUserIdList) {
        log.info("当前用户Id："+userId);
        log.info("节点办理人id："+nodeUserIdList);
        //指定用户id集合
        List<String> nodeUserList=Arrays.asList(nodeUserIdList.split(","));
        if (nodeUserList.contains(String.valueOf(userId))){
            log.info("用户"+userId+"在用户集合["+nodeUserIdList+"]中,满足流程查看权限");
            return true;
        }
        return false;
    }

    /**
     * 变更单修改权限
     * @param currentStep
     * @param userId
     * @param nodeUserIdList
     * @param currentStepString
     * @return
     */
    @Override
    public Boolean isMeet(String currentStep, Integer userId, String nodeUserIdList, String currentStepString) {
        log.info("当前节点名称："+currentStep);
        log.info("指定节点名称："+currentStepString);
        //指定流程步骤集合(编辑;修改)
        List<String> currentStepList = Arrays.asList(currentStepString.split(";"));
        //指定用户id集合
        List<String> nodeUserList=Arrays.asList(nodeUserIdList.split(","));
        if (nodeUserList.contains(String.valueOf(userId)) && currentStepList.contains(currentStep)){
            log.info("用户"+userId+"在用户集合["+nodeUserIdList+"]中,满足流程修改权限");
            return true;
        }
        return false;
    }
}
